package cac.fenjian.resource.outBill.service;


import cac.common.CreatMsgId;
import cac.fenjian.resource.outBill.dao.ReturnApplyDao;
import cac.fenjian.resource.outBill.dao.WmsInvOutBillHDao;
import cac.fenjian.resource.outBill.dao.WmsInvOutBillLDao;
import cac.fenjian.resource.wmsdeliverplan.dao.WmsDeliverPlanDao;
import cac.gkinterface.service.WorkService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.cac.dme.adapter.utils.ComUtil;
import com.cac.dme.common.exception.service.DaoException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@Service
@Slf4j
public class WmsInvOutBillService {
    @Autowired
    private WmsInvOutBillHDao wmsInvOutBillHDao;

    @Autowired
    private WmsInvOutBillLDao wmsInvOutBillLDao;

    @Autowired
    private ReturnApplyDao returnApplyDao;

    @Autowired
    private Environment environment;
    @Autowired
    private WorkService workService;
    @Autowired
    private WmsDeliverPlanDao wmsDeliverPlanDao;
    /**
     * 批量新增数据
     * @param map
     * @return
     */
    @Transactional
    public int insertWmsInvOutBillHMany(Map map){
        try{
            String wmsInvOutBillHId = ComUtil.getId();
            wmsInvOutBillHDao.insertWmsInvOutBillH(map,wmsInvOutBillHId);
            String wmsInvOutBillLId = ComUtil.getId();
            wmsInvOutBillLDao.insertWmsInvOutBillL(map,wmsInvOutBillLId,wmsInvOutBillHId);
            map.put("wmsInvOutBillLId",wmsInvOutBillLId);
            map.put("wmsInvOutBillHId",wmsInvOutBillHId);
            return wmsInvOutBillLDao.insertWmsInventoryTransaction(map);

        }catch (Exception e){
            throw  new DaoException(e.getMessage(),e);
        }
    }
    //成品、零件退库
    @Transactional
    public String applyCancelStock(Map map1,String IP){
        String wmsReturnApplyId = (String) map1.get("wmsReturnApplyId");
        String msgId = CreatMsgId.getMsgId();
        HashMap deliveryBack = returnApplyDao.searchDliveryBack(map1);
        String erpWmsDliveryId=null;
        if(deliveryBack != null){
            erpWmsDliveryId = (String) deliveryBack.get("ATTRIBUTE3");
        }
        map1.put("erpWmsDliveryId",null);
        if(erpWmsDliveryId != null){
            map1.replace("erpWmsDliveryId",erpWmsDliveryId);
        }
        //获取配置文件中的请求路径
        HashMap map = returnApplyDao.applyCancelStock(map1);
        if(environment.getProperty("returnUnkowm.debug").equals("true")){
            //查询当前回退的交接单
            HashMap ret = wmsDeliverPlanDao.searchDeliveryType((String)map1.get("wmsDeliveryPlanId"));
            if("143".equals(ret.get("requireShop"))){
                map.put("applyDeptId",ret.get("requireOrgCode"));
                map.put("backDeptId",ret.get("requireOrgCode"));
                map.put("backShop",environment.getProperty("returnUnkowm.shop143.backShop"));
            }else{
                map.put("applyDeptId",ret.get("requireOrgCode"));
                map.put("backDeptId",ret.get("requireOrgCode"));
                map.put("backShop",environment.getProperty("returnUnkowm.shop190.backShop"));
            }
        }

        map.put("userIp",IP);
        log.info(">>>>>>>>>map:"+map);
        HashMap issuedTest = new HashMap();
        JSONObject headersMap = new JSONObject();
        issuedTest.put("type", environment.getProperty("doReturnErp.applyCancelStock.func"));
        String str = JSON.toJSONString(map,(ValueFilter)(obj, name, value)->{
            if(value==null){
                return "";
            }
            return value;
        });
        JSONObject data = JSON.parseObject(str);
        log.info("数据转换==BData===="+data.toJSONString());
        headersMap.put("func",environment.getProperty("doReturnErp.applyCancelStock.func"));
        headersMap.put("data",data);
        headersMap.put("msgId",msgId);
        log.info("工控网上传后台日志:>>>>>>>>>222222222>2222>>issuedParameters:" + issuedTest.toString());
        issuedTest.put("BData", headersMap.toJSONString());
        issuedTest.put("msgId", msgId);
        log.info("工控网传送数据:>>>>>>>>>>>"+headersMap.toJSONString());
        workService.issuedTest(issuedTest);
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersMap.toJSONString().getBytes());
        return BData;
    }

    //标准件退库
    @Transactional
    public String applyCancelStockBzj(Map map1,String IP){
        String wmsReturnApplyId = (String) map1.get("wmsReturnApplyId");
        String msgId = CreatMsgId.getMsgId();
        HashMap deliveryBack = returnApplyDao.searchDliveryBack(map1);
        String erpWmsDliveryId=null;
        if(deliveryBack != null){
            erpWmsDliveryId = (String) deliveryBack.get("ATTRIBUTE3");
        }
        map1.put("erpWmsDliveryId",null);
        if(erpWmsDliveryId != null){
            map1.replace("erpWmsDliveryId",erpWmsDliveryId);
        }
        //获取配置文件中的请求路径
        HashMap map = returnApplyDao.applyCancelStockBzj(map1);
        if(environment.getProperty("returnUnkowm.debug").equals("true")){
            //查询当前回退的交接单
            HashMap ret = wmsDeliverPlanDao.searchDeliveryType((String)map1.get("wmsDeliveryPlanId"));
            if("143".equals(ret.get("requireShop"))){
                map.put("applyDeptId",ret.get("requireOrgCode"));
                map.put("backDeptId",ret.get("requireOrgCode"));
                map.put("backShop",environment.getProperty("returnUnkowm.shop143.backShop"));
            }else{
                map.put("applyDeptId",ret.get("requireOrgCode"));
                map.put("backDeptId",ret.get("requireOrgCode"));
                map.put("backShop",environment.getProperty("returnUnkowm.shop190.backShop"));
            }
        }

        map.put("userIp",IP);
        log.info(">>>>>>>>>map:"+map);
        HashMap issuedTest = new HashMap();
        JSONObject headersMap = new JSONObject();
        issuedTest.put("type", "101-ERP-applyCancelStockBzj");
        String str = JSON.toJSONString(map,(ValueFilter)(obj, name, value)->{
            if(value==null){
                return "";
            }
            return value;
        });
        JSONObject data = JSON.parseObject(str);
        log.info("数据转换==BData===="+data.toJSONString());
        headersMap.put("func","101-ERP-applyCancelStockBzj");
        headersMap.put("data",data);
        headersMap.put("msgId",msgId);
        log.info("工控网上传后台日志:>>>>>>>>>2222222222222>>issuedParameters:" + issuedTest.toString());
        issuedTest.put("BData", headersMap.toJSONString());
        issuedTest.put("msgId", msgId);
        log.info("工控网传送数据:>>>>>>>>>>>"+headersMap.toJSONString());
        workService.issuedTest(issuedTest);
        //对已经转换成字符串的数据进行加密
        final Base64.Encoder encoder = Base64.getEncoder();
        String BData = encoder.encodeToString(headersMap.toJSONString().getBytes());
        return BData;
    }
    //分拣保存时插入占用表

    public int createOutAllotment(HashMap maps){
        return wmsInvOutBillHDao.createOutAllotment(maps);
    }
    //分拣保存时插入出库主表
    public int createOutBillH(HashMap map){
        return wmsInvOutBillHDao.createOutBillH(map);
    }
    //更新台账占用信息
    public int updateItemInventory(HashMap maps){
        return wmsInvOutBillHDao.updateItemInventory(maps);
    }

    //分拣占用
    public HashMap sortingAllot(HashMap maps){
        HashMap hashMap = wmsInvOutBillHDao.sortingAllot(maps);
        //查询AO_No
        hashMap.put("aoNo",maps.get("aoCode"));
        return hashMap;
    }
    //分拣出库
    public HashMap sortingInvOut(HashMap maps){
        return wmsInvOutBillHDao.sortingInvOut(maps);
    }
    //分拣占用取消
    public HashMap sortingAllotCancel(HashMap map) {
        return wmsInvOutBillHDao.sortingAllotCancel(map);
    }
    //分拣出库撤销
    public HashMap sortingInvOutCancel(HashMap map){
        return wmsInvOutBillHDao.sortingInvOutCancel(map);
    }

    //ERP出库保存101流水表,台账
    public int erpOutOccupyTransaction(HashMap map){
        //查询ERP出库的缓存箱以及出库的数量(存在单个缓存箱大于出库数量)
        HashMap hashMap = wmsInvOutBillHDao.outWorkbinQty(map);
        HashMap endMap = new HashMap();
        String wmsItemTransactionId = ComUtil.getId();
        map.put("wmsItemTransactionId",wmsItemTransactionId);
        try{
            if(hashMap==null){
                int allotmentQty = (Integer.parseInt(map.get("allotmentQty").toString())) ;
                //查询ERP出库的缓存箱以及出库的数量(单个缓存箱数量小于出库数量)
                List<HashMap> lessMaps = wmsInvOutBillHDao.outWorkbinLessQty(map);
                //遍历缓存箱，拿出物料
                int endQty = 0;
                for(int i = 0;i<lessMaps.size()-1;i++){
                    HashMap hashMap1 = lessMaps.get(i);
                    HashMap hashMap2 = lessMaps.get(i+1);
                    //获得第一个缓存箱中物料数量
                    int firstQty = Integer.parseInt(hashMap1.get("itemQty").toString());
                    //将缓存箱中物料数量减下来
                    endMap.put("workbinCode",hashMap1.get("workbinCode"));
                    endMap.put("msWorkbinMaterialId",hashMap1.get("msWorkbinMaterialId"));
                    endMap.put("allotmentQty",firstQty);
                    //ERP出库——更新库存表
                    wmsInvOutBillHDao.erpOutWorkbinMaterial(endMap);

                    //保存需要出库的erp缓存箱数据
                    endMap.put("wmsItemTransactionId",wmsItemTransactionId);
                    endMap.put("wmsItemInventoryId",map.get("wmsItemInventoryId"));
                    wmsInvOutBillHDao.insertErpOutBill(endMap);

                    //获得第二个缓存箱中物料数量
                    int secondQty = Integer.parseInt(hashMap2.get("itemQty").toString());
                    endQty = endQty+firstQty+secondQty;
                    //如果当前缓存箱累加数量小于erp出库数量，跳过下面代码，继续执行下一个循环
                    if(endQty< allotmentQty){
                        continue;
                    }
                    //确认最后一个箱子需要取出的物料数量
                    Integer lastQty = secondQty-(endQty - allotmentQty);
                    endMap.put("workbinCode",hashMap2.get("workbinCode"));
                    endMap.put("msWorkbinMaterialId",hashMap2.get("msWorkbinMaterialId"));
                    endMap.put("allotmentQty",lastQty);
                    //将缓存箱中物料数量减下来
                    wmsInvOutBillHDao.erpOutWorkbinMaterial(endMap);
                    endMap.put("wmsItemTransactionId",wmsItemTransactionId);
                    endMap.put("wmsItemInventoryId",map.get("wmsItemInventoryId"));
                    //保存需要出库的erp缓存箱数据
                    wmsInvOutBillHDao.insertErpOutBill(endMap);
                }
            }else{
                map.put("workbinCode",hashMap.get("workbinCode"));
                map.put("msWorkbinMaterialId",hashMap.get("msWorkbinMaterialId"));
                wmsInvOutBillHDao.erpOutWorkbinMaterial(map);
                wmsInvOutBillHDao.insertErpOutBill(map);
            }
        }catch (Exception e){

        }
        wmsInvOutBillHDao.erpOutOccupyInventory(map);
        return wmsInvOutBillHDao.erpOutOccupyTransaction(map);
    }
    //ERP出库占用——插入出库申请主表
    public int erpOutOccupyOutBillH(HashMap map){return wmsInvOutBillHDao.erpOutOccupyOutBillH(map);}

    //ERP出库占用——插入出库申请主表
    public int erpOutOccupyOutBillL(HashMap map){return wmsInvOutBillHDao.erpOutOccupyOutBillL(map);}

    //ERP占用取消
    public int InvOutAllotCancel(HashMap map){
        //查询需要取消占用的台账id
        HashMap hashMap = wmsInvOutBillHDao.inventoryCancelIds(map);
        wmsInvOutBillHDao.updateItemInventoryCancel(hashMap);
        wmsInvOutBillHDao.DeleteOutBillL(map);
        wmsInvOutBillHDao.DeleteOutBillH(map);
        return wmsInvOutBillHDao.InvOutAllotCancel(map);
    }

    //ERP出库占用——插入占用表
    public int erpOutOccupyAllotment(HashMap map){
        return wmsInvOutBillHDao.erpOutOccupyAllotment(map);
    }
    //ERP出库占用——修改台账
    public int erpUpdateInventory(HashMap map){
        return wmsInvOutBillHDao.erpUpdateInventory(map);
    }
    //ERP出库撤销
    public int erpOutOccupyCancel(HashMap map){
        //1.查询需要还原的台账id xiaojian 6-16
        List<HashMap> inventoryMaps = wmsInvOutBillHDao.backWmsInventory(map);
        for(HashMap inventoryMap:inventoryMaps){
            //2.查找该台账下需要恢复的缓存箱数据
            List<HashMap> workbinMaps = wmsInvOutBillHDao.backWorkbin(inventoryMap);
            //3.恢复缓存箱数据
            for(HashMap workbinMap:workbinMaps){
                wmsInvOutBillHDao.updateWorkbin(workbinMap);
                wmsInvOutBillHDao.repealErpWorkbin(workbinMap);
            }
        }
//        HashMap hashMap = wmsInvOutBillHDao.getOutCancelData(map);
//        wmsInvOutBillHDao.erpOutCancelWorkbinMaterial(hashMap);
        //查询需要还原的台账id
        List<HashMap> inventoryIds = wmsInvOutBillHDao.backInventoryIds(map);
        for(HashMap inventoryId:inventoryIds){
            //ERP出库撤销——修改台账表数据
            wmsInvOutBillHDao.updateInventory(inventoryId);
        }
        //ERP出库撤销——更改流水表数据
        return wmsInvOutBillHDao.erpOutOccupyCancel(map);
    }

    public int searchItemInventoryExists(HashMap map){
        return wmsInvOutBillHDao.searchItemInventoryExists(map);
    }

}
